package middleware

import (
	"cron_table_admin/config"
	"cron_table_admin/global"
	_ "cron_table_admin/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"time"
)

func ApiLogMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		startTime := time.Now()
		//解析query参数和form参数
		if err := ctx.Request.ParseForm(); err != nil {
			global.LOGGER.Error("api访问日志中间件，解析参数，出现异常", zap.Any("err", err))
		}
		log := global.LoggerWithContext(ctx)
		ctx.Next()
		//请求耗时
		r := ctx.Request
		duration := time.Since(startTime)
		mapResult := global.GetParameters(ctx)
		log.Info("用户访问日志", zap.String("ip", ctx.ClientIP()), zap.Any("method", r.Method), zap.Any("request path", r.URL.Path),
			zap.String("start", startTime.UTC().Format(config.TimeFormat)), zap.String("end", time.Now().UTC().Format(config.TimeFormat)), zap.Duration("request cost", duration), zap.Any("resParameters:", mapResult))
	}
}
